import 'dart:io';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:read_flutter_test/page/reading_page.dart';
import 'package:read_flutter_test/service/player_service.dart';
import 'package:read_flutter_test/utils/assets_to_file_utils.dart';
import 'package:read_flutter_test/utils/get_path/get_base_path.dart';
import 'package:read_flutter_test/utils/get_path/get_temp_dir.dart';
import 'package:read_flutter_test/utils/toast/common.dart';
import 'package:url_launcher/url_launcher.dart';
import 'bean/book.dart';
import 'config/shared_preference_provider.dart';

WebViewEnvironment? webViewEnvironment;

final navigatorKey = GlobalKey<NavigatorState>();

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Prefs().initPrefs();

  initBasePath();
  await Server().start();

  SmartDialog.config.custom = SmartConfigCustom(
    maskColor: Colors.black.withOpacity(0.35),
    useAnimation: true,
    animationType: SmartAnimationType.centerFade_otherSlide,
  );
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
      navigatorKey: navigatorKey,
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  //初始化判断是否有webView2 如果没有则进行下载
  late Book _book;

  void initState() {
    super.initState();
    AnxToast.init(context);
    initInAppWebView();
  }

  Future<void> initInAppWebView() async {
    // 获取WebView2的版本信息
    if (!kIsWeb && defaultTargetPlatform == TargetPlatform.windows) {
      final availableVersion = await WebViewEnvironment.getAvailableVersion();
      print("WebView version: $availableVersion");
      if (availableVersion == null) {
        //写一个对话框
        await showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text('WebView2未安装'),
              content: Text('请安装WebView2后再试。'),
              actions: [
                TextButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: Text('取消'),
                ),
                TextButton(
                  child: Text("确定"),
                  onPressed: () async {
                    launchUrl(
                      Uri.parse(
                        'https://developer.microsoft.com/en-us/microsoft-edge/webview2',
                      ),
                      mode: LaunchMode.externalApplication,
                    );
                  },
                ),
              ],
            );
          },
        );
      } else {
        webViewEnvironment = await WebViewEnvironment.create(
          settings: WebViewEnvironmentSettings(
            userDataFolder: (await getAnxTempDir()).path,
          ),
        );
      }
    }
  }

  String displayText = "电子书信息";

  Future<String> getEpubInfo() async {
    try {
      // 获取asset文件路径
      final ByteData data = await DefaultAssetBundle.of(
        context,
      ).load('assets/epub/贫穷的本质：我们为什么摆脱不了贫穷.epub');
      final bytes = data.buffer.asUint8List();
      // 返回基本信息
      return '''
文件名: 贫穷的本质：我们为什么摆脱不了贫穷.epub
文件大小: ${(bytes.length / 1024).toStringAsFixed(2)} KB
''';
    } catch (e) {
      return '读取文件失败: $e';
    }
  }

  void _importBook() async {
    // 打开文件选择器
    final result = await FilePicker.platform.pickFiles(
      type: FileType.custom,
      allowedExtensions: ['epub'],
    );

    if (result != null) {
      // 获取选中文件的路径
      final filePath = result.files.single.path;
      print("==========filePath==========${filePath}");
      // 读取文件内容
      final file = File(filePath!);
      // final fileContent = await file.readAsBytes();
      print("===拿到的文件数据===${file.toString()}");
      String serverFileName = Server().setTempFile(file);
      String bookUrl = "http://localhost:${Server().port}/$serverFileName";
      print("======serverFileName==========" + serverFileName);
      print("======bookUrl==========" + bookUrl);
      AssetsToFileUtils.saveBook(file, "书名", "作者", "description", "cover").then(
            (book) {
          _book = book;
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => ReadingPage(book: _book, cfi: ""),
            ),
          );
        },
      );
      // 保存文件到临时目录
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
        actions: [
          IconButton(icon: const Icon(Icons.add), onPressed: _importBook),
        ],
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text("读取电子书"),
            TextButton(
              onPressed: () {
                getBook();
                //跳转到电子书页面
                // Navigator.push(
                //   context,
                //   MaterialPageRoute(builder: (context) => BookReadPage(
                //     // Key? key,
                //     // required Function showOrHideAppBarAndBottomBar,
                //     // required Book book,
                //     // String? cfi,
                //     // required Function onLoadEnd,
                //   )),
                // );
              },
              child: Text("打开电子书"),
            ),

            TextButton(
              onPressed: () async {
                final info = await getEpubInfo();
                setState(() {
                  displayText = info;
                });
              },
              child: Text("点击从assets中读取epub电子书"),
            ),
            Expanded(child: Text(displayText)),
          ],
        ),
      ),
    );
  }

  //打开电子书操作
  void getBook() {
    //从系统中拿去epub文件

    AssetsToFileUtils.readAndSaveEpub(context).then((file) {
      print("===拿到的文件数据===${file.toString()}");
      String serverFileName = Server().setTempFile(file);
      String bookUrl = "http://localhost:${Server().port}/$serverFileName";
      print("======serverFileName==========" + serverFileName);
      print("======bookUrl==========" + bookUrl);
      AssetsToFileUtils.saveBook(file, "书名", "作者", "description", "cover").then(
        (book) {
          _book = book;
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => ReadingPage(book: _book, cfi: ""),
            ),
          );
        },
      );
    });
  }

  Future<void> onLoadEnd() async {}

  void showOrHideAppBarAndBottomBar(bool show) {}
}
